<template>
	<view class="order-list-container">
		<!-- 头部搜索区 -->
		<view class="search-section">
			<view class="search-box">
				<uni-icons type="search" size="16" color="#666"></uni-icons>
				<input type="text" v-model="searchKey" placeholder="搜索订单号" @input="onSearchInput" />
			</view>
		</view>

		<!-- 订单状态标签 -->
		<view class="status-tabs">
			<view 
				v-for="(item, index) in statusList" 
				:key="index"
				:class="['tab-item', currentStatus === index ? 'active' : '']"
				@tap="switchStatus(index)"
			>
				<text>{{item.name}}</text>
				<text class="count">({{item.count}})</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view 
			scroll-y 
			class="order-list" 
			@scrolltolower="loadMore"
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<template v-if="orderList.length > 0">
				<OrderCard 
					v-for="(order, index) in orderList" 
					:key="index" 
					:order="order"
				>
					<template #actions>
						
						<button class="btn" v-if="order.status === 1" @tap="goToDelivery(order)">发货</button>
					</template>
				</OrderCard>
			</template>
			<template v-else>
				<view class="empty-wrapper">
					<uv-empty
						mode="order"
						text="暂无订单数据"
						:marginTop="0"
					></uv-empty>
				</view>
			</template>
		</scroll-view>
	</view>
</template>

<script>
	import OrderCard from '@/components/OrderCard/OrderCard.vue'
	import { formatDate } from '@/utils/date.js'
	
	export default {
		components: {
			OrderCard
		},
		data() {
			return {
				searchKey: '',
				currentStatus: 0,
				statusList: [
					{ name: '全部', count: 0 },
					{ name: '待发货', count: 0 },
					{ name: '已发货', count: 0 },
					{ name: '已完成', count: 0 },
					{ name: '已取消', count: 0 }
				],
				orderList: [],
				pageNum: 1,
				pageSize: 10,
				loading: false,
				hasMore: true,
				merchantId: null,
				refreshing: false
			}
		},
		onLoad(options) {
			this.merchantId = options.merchantId
			
			if (this.merchantId) {
				this.getHeadCount()
				this.getOrderList()
			} else {
				uni.showToast({
					title: '缺少商家ID参数',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}
		},
		methods: {
			formatDate,
			switchStatus(index) {
				this.currentStatus = index
				this.pageNum = 1
				this.orderList = []
				this.hasMore = true
				this.getOrderList()
			},
			async getOrderList() {
				if (this.loading || !this.hasMore) return
				this.loading = true
				
				try {
					const params = {
						status: this.currentStatus === 0 ? -1 : this.getStatusCode(this.currentStatus),
						keyWord: this.searchKey.trim(),
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						merchantId: this.merchantId
					}
					
					const res = await this.$http.post('/merchant/order/list', params)
					
					if (res) {
						const { items = [], count = 0 } = res || {}
						
						if (this.pageNum === 1) {
							this.orderList = items
						} else {
							this.orderList = [...this.orderList, ...items]
						}
						
						this.hasMore = this.orderList.length < count
						
						if (items.length > 0) {
							this.pageNum++
						}
					}
				} catch (error) {
					console.error('获取订单列表失败', error)
					uni.showToast({
						title: '获取订单列表失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},
			getStatusCode(index) {
				const statusMap = {
					0: -1,
					1: 1,
					2: 6,
					3: 2,
					4: 3
				}
				return statusMap[index]
			},
			loadMore() {
				if (!this.loading && this.hasMore) {
					this.getOrderList()
				}
			},
			async getHeadCount() {
				try {
					const res = await this.$http.get(`/merchant/order/head?merchantId=${this.merchantId}`)
					if (res) {
						const counts = res
						this.statusList = [
							{ name: '全部', count: counts.all || 0 },
							{ name: '待发货', count: counts.waitShip || 0 },
							{ name: '已发货', count: counts.shipped || 0 },
							{ name: '已完成', count: counts.completed || 0 },
							{ name: '已取消', count: counts.cancelled || 0 }
						]
					}
				} catch (error) {
					console.error('获取订单统计失败', error)
					uni.showToast({
						title: '获取订单统计失败',
						icon: 'none'
					})
				}
			},
			refreshCounts() {
				this.getHeadCount()
			},
			// 跳转到发货页面
			goToDelivery(order) {
				uni.navigateTo({
					url: `/subpkg/goods_delivery_page/goods_delivery_page?orderId=${order.id}`
				})
			},
			// 搜索输入处理
			onSearchInput() {
				// 重置分页
				this.pageNum = 1
				this.orderList = []
				this.hasMore = true
				
				// 使用防抖进行搜索
				uni.$uv.debounce(() => {
					this.getOrderList()
				}, 500)
			},
			// 处理下拉刷新
			async onRefresh() {
				this.refreshing = true
				// 重置分页
				this.pageNum = 1
				this.orderList = []
				this.hasMore = true
				
				try {
					// 刷新头部统计
					await this.getHeadCount()
					// 刷新订单列表
					await this.getOrderList()
				} catch (error) {
					console.error('刷新失败', error)
					uni.showToast({
						title: '刷新失败',
						icon: 'none'
					})
				} finally {
					this.refreshing = false
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'merchant_order_list.scss';
</style>